package wang.xinqiu.mysqlcontrol.ui

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import wang.xinqiu.mysqlcontrol.data.MySQLManager

@Composable
fun SessionStatusBar(
    mysqlManager: MySQLManager,
    modifier: Modifier = Modifier
) {
    var sessionDuration by remember { mutableStateOf(0L) }
    var isExpired by remember { mutableStateOf(false) }
    
    LaunchedEffect(Unit) {
        while (true) {
            sessionDuration = mysqlManager.getSessionDurationSeconds()
            isExpired = mysqlManager.isSessionExpired()
            delay(1000) // 每秒更新一次
        }
    }
    
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = if (isExpired) MaterialTheme.colorScheme.errorContainer else MaterialTheme.colorScheme.primaryContainer,
        tonalElevation = 2.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = if (isExpired) "会话已过期" else "会话活跃",
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium,
                color = if (isExpired) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onPrimaryContainer
            )
            
            Text(
                text = formatDuration(sessionDuration),
                fontSize = 14.sp,
                color = if (isExpired) MaterialTheme.colorScheme.onErrorContainer else MaterialTheme.colorScheme.onPrimaryContainer
            )
        }
    }
}

private fun formatDuration(seconds: Long): String {
    val hours = seconds / 3600
    val minutes = (seconds % 3600) / 60
    val secs = seconds % 60
    
    return when {
        hours > 0 -> String.format("%02d:%02d:%02d", hours, minutes, secs)
        minutes > 0 -> String.format("%02d:%02d", minutes, secs)
        else -> String.format("00:%02d", secs)
    }
}